package com.example.carconsumer.controller.dl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import com.example.carinterface.pojo.Driver;
import com.example.carinterface.pojo.Login;
import com.example.carinterface.pojo.User;
import com.example.carinterface.pojo.Worker;
import com.example.carinterface.service.dl.LoginService;
import com.example.carinterface.service.dl.admin.OrderService;
import com.example.carinterface.utils.ResultJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.deploy.util.StringUtils;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Api(value = "账号操作", tags = "账号相关操作")
@RestController
@RequestMapping("/accountControl")
@CrossOrigin
public class LoginController {

    @Reference(check = false)
    private LoginService loginService;
    @Reference(check = false)
    private OrderService orderService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "司机登录", responseReference = "返回司机")
    @PostMapping("/driverLogin")
    public ResultJson<Driver> userLogin(@ApiParam(name = "map", value = "" +
            "tel:电话，" +
            "password：密码") @RequestBody Driver driver) {
        UsernamePasswordToken token = new UsernamePasswordToken(driver.getTel(), driver.getPassword());

        Subject subject = SecurityUtils.getSubject();
        ResultJson<Driver> resultJson = new ResultJson<>();
        try {
            subject.login(token);
//            loginService.getPermission(map);
            //登录成功过获取司机
            Driver worker = loginService.findDriver(driver.getTel());
            resultJson.setSuccess("登陆成功", worker);
        } catch (UnknownAccountException e) {
            resultJson.setFail("用户名不存在");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            resultJson.setFail("登录失败");
        }
        return resultJson;

    }

    @ApiOperation("后台登录")
    @PostMapping("/adminLogin")
    public ResultJson<Worker> adminLogin(@RequestBody Login login) {
        UsernamePasswordToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword());

        Subject subject = SecurityUtils.getSubject();
        ResultJson<Worker> resultJson = new ResultJson<>();
        try {
            subject.login(token);
//            loginService.getPermission(map);
            //登录成功过获取司机
            Worker worker = loginService.findWorker(login.getUsername());
            resultJson.setSuccess("登陆成功", worker);
        } catch (UnknownAccountException e) {
            resultJson.setFail("用户名不存在");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            resultJson.setFail("登录失败");
        }
        return resultJson;
    }


    @ApiOperation("发送邮箱验证")
    @PostMapping("sendEmailCode")
    public ResultJson<String> emailCode(@ApiParam(name = "map", value = "username:用户名，email:邮箱") @RequestBody Map<String, String> map) {
        ResultJson<String> resultJson = new ResultJson<>();
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        map.put("code", code);

        if (loginService.FindLoginByUsernameAndEmail(map) !=null) {
            //匹配用户名和邮箱成功

            boolean b = loginService.sendEmail(map);
            if (b) {
                //发送成功 ,存放到redis中
                redisTemplate.opsForValue().set(map.get("email"), code, 60, TimeUnit.MINUTES);
                resultJson.setSuccess("发送成功");
            } else {
                resultJson.setFail("发送失败");
            }

        } else {
            resultJson.setFail("用户名和邮箱不匹配");
        }


        return resultJson;
    }

    @ApiOperation("校验邮箱验证码")
    @PostMapping("/checkEmailCode")
    public ResultJson<String> checkEmailCode(@ApiParam(name = "map", value = "email:邮箱，" +
            "code:验证码," +
            "newPassword:新密码," +
            "username:用户名") @RequestBody Map<String, String> map) {
        ResultJson<String> resultJson = new ResultJson<>();
        String redisEmailCode = redisTemplate.opsForValue().get(map.get("email"));
        if (redisEmailCode != null && redisEmailCode.equalsIgnoreCase(map.get("code"))) {
            //验证成功
            resultJson.setData("验证成功");
            //开始修改密码
            //设置加密后的新密码
            SimpleHash newPassword = new SimpleHash("md5", map.get("newPassword"), map.get("username"), 32);

            map.put("newPassword", newPassword.toString());

            if (loginService.updateLoginPassword(map) == 1) {
                resultJson.setSuccess("修改密码成功");
            } else {
                resultJson.setFail("修改密码失败");
            }

        } else {
            resultJson.setFail("验证失败");
        }
        return resultJson;
    }


    @ApiOperation("发送手机验证")
    @PostMapping("/sendPhoneCode")
    public ResultJson sendPhoneCode(@ApiParam(name = "tel", value = "tel: 手机号码") @RequestBody Map<String, String> telMap) {
        String tel = telMap.get("tel");
        StringBuilder sb_code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb_code.append(random.nextInt(10));
        }
        String code = sb_code.toString();
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);


        boolean flag = loginService.senSms(tel, LoginService.templateCode, param);
        ResultJson resultJson = new ResultJson();
        if (flag) {
            //存放在redis中
            redisTemplate.opsForValue().set(tel, code, 5, TimeUnit.MINUTES);
            resultJson.setSuccess("发送成功", code);
        } else {
            resultJson.setFail("发送失败");
        }
        return resultJson;
    }

    @ApiOperation("验证手机验证码")
    @PostMapping("/checkPhoneCode")
    public ResultJson<User> checkPhoneCode(@ApiParam(name = "map", value = "tel:手机号，" +
            "code:验证码") @RequestBody Map<String, String> map) {

        ResultJson<User> resultJson = new ResultJson<>();
        String redisTelCode = redisTemplate.opsForValue().get(map.get("tel"));
        if (redisTelCode != null && redisTelCode.equals(map.get("code"))) {
            //验证成功
            resultJson.setSuccess("验证成功");
            //如果用户已存在，返回user。如果用户不存在，就创建用户，并且让用户完善信息
            User user = loginService.findUser(map.get("tel"));
            if (user != null) {
                //有用户
                resultJson.setData(user);
                //判断是否有车主卡
                List<Map<String, Object>> data = orderService.findAllOwnerCardByUserId(user.getId()).getData();
                if (data==null||data.size()==0){
                    resultJson.setSuccess("没有车主卡","00");
                }else {
                    resultJson.setSuccess("有车主卡","11");
                }
                if (user.getIdCard()==null){
                    resultJson.setCode("0");
                }
            }else {
                //没有用户，创建
               User noInfoUser =  loginService.addUserByTel(map);
               resultJson.setData(noInfoUser);
//               没有完善信息
               resultJson.setCode("0");
            }


        } else {
            resultJson.setFail("验证失败");
        }
        return resultJson;
    }


    @PostMapping("/addDriver")
    public ResultJson addDriver() {

        return null;


    }


}
